import React from 'react';
import { connect } from 'react-redux';
import {  Tree } from 'antd';
import { getCategories} from  "../../../actions/categoryActions";
import { listToTree } from '../../common' ; 
var _ = require('lodash');

const TreeNode = Tree.TreeNode;

import "./style.css";
//相比起CategoryTree，SimpleCategory着重于显示树的内容，而不支持一系列诸如添加，删除，重命名的功能。
class SimpleCategoryTree extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            expandedKeys: ['0',],
            autoExpandParent: true,
            checkedKeys: ['0'],
            selectedKeys: ['0'],
            treeData:{},
        };
    }

    componentDidMount(){
        this.props.getCategories().then(
            (res) =>{ console.log("already get categories!"); }
        );
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onSelect = (selectedKeys, info) => {
        if ( info.selected ) {
            this.setState({ selectedKeys });
            this.props.onSelect(selectedKeys[0]);
        }
    }
    
    render(){
        const loop = data => Object.keys(data).map ( (item) => {
            let node = data[item];
            const title = node.title;
            if ( _.isEmpty(node.children) ) {
                return <TreeNode title={title} key={item} isLeaf={true}/>;
            }else {
                return <TreeNode title={title} key={item}>{loop(node.children)}</TreeNode>;
            }
        });

        return (
            <div className="category-tree-container">
                <Tree
                    showLine className="myCls"
                    treeDefaultExpandAll
                    onExpand={this.onExpand} expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onSelect={this.onSelect} selectedKeys={this.state.selectedKeys}
                    >
                            {loop(this.props.treeData)}
                    </Tree> 
            </div>
        )
    }
}

const mapStateToProps = (state) => {
  return {
     treeData: listToTree(state.category.categories ,{
                            idKey: 'id',
                            parentKey: 'parent_id',
                            childrenKey: 'children'
                        })
   }
}

SimpleCategoryTree.propTypes = {
    getCategories:React.PropTypes.func.isRequired,
};

export default connect(mapStateToProps,{getCategories})(SimpleCategoryTree);